<?php
	session_start();
	include_once 'member.php';
	//$conn = mysql_connect('sql302.byethost3.com', 'b3_11891689', '396121');
//	mysql_select_db("b3_11891689_fbapp",$conn);
 	$conn = mysql_connect('localhost', 'vinasoftwa_g6', 'Uppercase1');
 	mysql_select_db("vinasoftwa_g6p2",$conn);
	mysql_query("SET character_set_results=utf8", $conn);
	mb_language('uni');
	mb_internal_encoding('UTF-8');
	mysql_query("set names 'utf8'",$conn);
/**
 *    FUNCTIONS FOR ADMIN's TASKS HANDLING.
 */
	/**
	 * Login action
	 */
	function checkAdminLogin($adname, $adpsw){
		$adname = mysql_real_escape_string($adname);
		$adpsw = mysql_real_escape_string($adpsw);
		$query = "SELECT * FROM admin WHERE name = '$adname' AND password = '$adpsw'";
		$rs = mysql_query($query);
		if($rs != null && mysql_num_rows($rs) > 0) return true;
		return false;
	}
	/**
	 * Get danh sach all nguoi diem cao nhat
	 */
	function getListMemberByPointsGained(){
		$query = "SELECT * FROM  `member` ORDER BY total_point DESC";
		$ret = array();
		$resultset = mysql_query($query);
		//Dua het vao array roi dung ham tao ra json
		if($resultset != null){
			while($rows = mysql_fetch_assoc($resultset)){
				$ret[] = $rows;				
			}
		}
		// return json:
		if(count($ret) > 0){
			return (json_encode($ret));
		}
		return "{\"id\":\"get-data\",\"result\":\"failed\"}";//json_encode($_err);
	}	
	/**
	 * Get danh sach 10 nguoi moi duoc nhieu ban be nhat
	 */
	
	function getListMemberByFriendInvited(){// not finished yet
		$query = "SELECT * FROM  `member` ORDER BY total_point DESC LIMIT 0 , 10";
		$ret = array();
		$resultset = mysql_query($query);
		//Dua het vao array roi dung ham tao ra json
		if($resultset != null){
			while($rows = mysql_fetch_array($resultset)){
				$tmp = new Member();
				$tmp->id = $rows['id'];
				$tmp->displayname = $rows['name'];
				$tmp->email = $rows['email'];
				$tmp->phoneno = $rows['phoneno'];
				$tmp->so_luot_choi_con_lai = $rows['so_luot_choi_con_lai'];
				$tmp->so_luot_da_choi = $rows['so_luot_da_choi'];
				$tmp->so_luot_choi_ref_con_lai = $rows['so_luot_choi_ref_con_lai'];
				$tmp->total_point = $rows['total_point'];
				$tmp->is_lucky = $rows['is_lucky'];
				array_push($ret, $tmp);
			}
		}
		// return json:
		if(count($ret) > 0){
			return json_decode(json_encode($ret));
		}
		return "{\"id\":\"getListMemberByPointsGained\",\"result\":\"failed\"}";
	}

	/**
	 * Change password, return 1 if successful, otherwise 0
	 */
	function adminChangePassword($oldpassword,$newpassword){
		$oldpassword = mysql_real_escape_string($oldpassword);
		$newpassword = mysql_real_escape_string($newpassword);
		$query = "SELECT * FROM admin WHERE password = '$oldpassword'";
		$rs = mysql_query($query);
// 		return "{\"count\":\"". mysql_num_rows($rs) ."-".$oldpassword."\"}";
		if($rs != null && mysql_num_rows($rs) > 0){
			$query = "UPDATE admin SET password = '$newpassword' WHERE password = '$oldpassword'";
			mysql_query($query);
			return true;
		}
		return false;
	}
	/**
	 * Delete member
	 */
	function deleteMember($id){
		$query = "DELETE FROM member WHERE id = ".$id;
		mysql_query($query);
		return true;	
	}
	
/**
 *    FUNCTIONS FOR MEMBER's TASKS HANDLING.
 */	
	
	/**
	 * Count members
	 * 
	 */
	function getNumberOfMember(){
		$query = "SELECT COUNT(*) as total FROM member";
		$rs = mysql_query($query);
		if($rs != null && mysql_num_rows($rs) > 0){
			while ($rows = mysql_fetch_assoc($rs)){
				$pages = intval($rows["total"]);
				return $pages;
			}
		}
		return 0;
	}
	
	/**
	 * Kiem tra xem nguoi dung con luot choi nua ko
	 */
	function checkIfMemberHasMoreTurns(){
		$query = "SELECT so_luot_choi_con_lai, so_luot_choi_ref_con_lai FROM member WHERE id = ". $_SESSION ["user"] ;
		$resultset = mysql_query($query);
// 		echo $query;
		//Dua het vao array roi dung ham tao ra json
		if($resultset != null){
			while($rows = mysql_fetch_assoc($resultset)){
				$s1 = intval($rows["so_luot_choi_con_lai"]);
				$s2 = intval($rows["so_luot_choi_ref_con_lai"]);
				if($s1 + $s2 <= 0) return false;
				if($s2 > 0) $s2 --;
				else if($s1 > 0) $s1--;
				mysql_query("UPDATE member SET so_luot_choi_con_lai=$s1,so_luot_choi_ref_con_lai=$s2  WHERE  id = ". $_SESSION ["user"]);
				return true;
			}
		}
		return false;
	}
// 	checkIfMemberHasMoreTurns();
	/**
	 * Kiem tra xem co kha nang nhan dc qua tang may man ko.
	 */
	function checkIfMemberCanReceiveDailyGift(){
		//1. Kiem tra user co nhan dc qua lan nao chua.
		$query1 = "SELECT * FROM member WHERE id = ".$_SESSION ["user"]." AND is_lucky = 1";		
		$rs1 = mysql_query($query1);
		if($rs1 != null && mysql_num_rows($rs1) <= 0) return true;
		//2. Kiem tra ngay hom nay co ai nhan dc qua chua
		$query2 = "SELECT * FROM gift_history WHERE date = CURDATE()";
		$rs2 = mysql_query($query2);
		if($rs2 != null && mysql_num_rows($rs2) <= 0) return true;
		return false;
	}
	
	/**
	 * Log to DB
	 */
	function saveToDatabase($v){
		$value = intval($v);		
		if($value <= 0) return;
		// Cap nhat bang member
		$is_lucky = 0;
		$q1 = "";
		if($value == 50000) {
			$is_lucky = 1;
			$q1 = "UPDATE member SET so_luot_da_choi = so_luot_da_choi + 1, is_lucky = 1 WHERE id = ".$_SESSION["user"];
		}
		else 
			if($value == 100){
				$q1 = "UPDATE member SET so_luot_da_choi = so_luot_da_choi + 1, total_point = total_point + total_point WHERE id = ".$_SESSION["user"];
			}
			else
			$q1 = "UPDATE member SET so_luot_da_choi = so_luot_da_choi + 1, total_point = total_point+$value WHERE id = ".$_SESSION["user"];
		mysql_query($q1);
	// Get ra cai luot choi kia
		$q2 = "SELECT so_luot_da_choi FROM member WHERE id=".$_SESSION["user"];
		$resultset = mysql_query($q2);
		if($resultset != null){
			if($rows = mysql_fetch_array($resultset)){
				$luot_choi = $rows["so_luot_da_choi"];
			}
		}
		// Cap nhat table member_history
		$q3 = "INSERT INTO `member_history`(`id`, `member_id`, `date`, `points_gained`, `luot_choi`)".
		" VALUES (NULL,".$_SESSION["user"].",CURDATE(),$value,$luot_choi)";
		mysql_query($q3);
		// Cap nhat gift_history
		if($value == 50000){
			$q4 = "INSERT INTO `gift_history`(`id`, `member_id`, `gift`, `date`) ".
				"VALUES (NULL,".$_SESSION["user"].",'Mobile Card',CURDATE())";
			mysql_query($q4);
		}
		
	}
	/**
	 * Xu li khi verify email
	 */
	function verifyAccount($email,$phone){
		$query = "UPDATE member SET email = '$email', phoneno = '$phone' WHERE id= ".$_SESSION["user"];
		mysql_query($query);
		$length = 10;
		$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$randomString = '';
		for ($i = 0; $i < $length; $i++) {
			$randomString .= $characters[rand(0, strlen($characters) - 1)];
		}
		$query2 = "INSERT INTO `activate`(`id`, `member_id`, `activate_code`)"
				." VALUES (null,".$_SESSION["user"].",'$randomString')";
		mysql_query($query2);
		return $randomString;
	}
	/**
	 * Activate account
	 */
	function activate($id,$activate_code){
// // 		echo $id.$activate_code;
// 		// Verify that activate_code is correct for this id
// 		$id = mysql_real_string($id);
// 		$activate_code = mysql_escape_string($activate_code);
// 		$query = "SELECT * FROM activate WHERE member_id = $id AND activate_code = '$activate_code'";
// 		echo $query;
// 		$rs1 = mysql_query($query);
// 		if($rs1 != null && mysql_num_rows($rs1) > 0){
// 			// Update new status for that user
// 			$query = "UPDATE member SET is_activated = 1 WHERE id = $id";
// 			mysql_query($query);
// 			echo "<br/>".$query;
// 			// Ok, now delete that record in activate table.
// 			$query = "DELETE FROM activate WHERE member_id = $id";
// 			mysql_query($query);
// 			echo "<br/>".$query;
// 			return true;
// 		}
// 		return false;
	}
	/**
	 * Cancel register, used for the link inside activate mail.
	 */
	function cancelRegister($id, $activate_code){
		$id = mysql_real_escape_string($id);
		$activate_code = mysql_real_escape_string($activate_code);
		$query1 = "DELETE FROM ACTIVATE WHERE member_id = $id AND activate_code = '$activate_code'";
		mysql_query($query1);
	}
	
	/**
	 * Get top 10 players
	 */
	function getTop10(){
		$query = "SELECT name,total_point FROM  `member` ORDER BY total_point DESC LIMIT 0,9";
		$ret = array();
		$resultset = mysql_query($query);
		//Dua het vao array roi dung ham tao ra json
		if($resultset != null){
			while($rows = mysql_fetch_assoc($resultset)){
				$ret[] = $rows;
			}
		}
		// return json:
		if(count($ret) > 0){
			return (($ret));
		}
		return array("id"=>"get-top-10","result" => "failed");
	}
	/**
	 * Get current player
	 */
	function getCurrentInfo(){
		$query = "SELECT name,so_luot_da_choi,total_point FROM member WHERE id = ".$_SESSION["user"];
		//echo $query;
		$resultset = mysql_query($query);
		$ret = array();
		if($resultset != null){
			while($rows = mysql_fetch_assoc($resultset)){
				$ret[] = $rows;
			}
		}
		// return json:
		if(count($ret) > 0){
			return (($ret));
		}
		return array("id"=>"get-current","result" => "failed");
	}
	/**
	 * Get current player
	 */
	function lastFunction(){
		$query = "SELECT so_luot_da_choi,ngay_tham_gia,total_point FROM member WHERE id = ".$_SESSION["user"];
		//echo $query;
		$resultset = mysql_query($query);
		$ret = array();
		if($resultset != null){
			while($rows = mysql_fetch_assoc($resultset)){
				$ret[] = $rows;
			}
		}
		// return json:
		if(count($ret) > 0){
			return (($ret));
		}
		return array("id"=>"get-current","result" => "failed");
	}
	//getCurrentInfo();
	/**
	 * Check if user fbid is exist
	 */
	function processLogin($fgid,$fbfullname,$email,$forg){
		if($forg == 0){
			// la fb
			$_SESSION["forg"] = 0;
		}
		else if($forg == 1){
			// la g+
			$_SESSION["forg"] = 1;
		}
		$query = "SELECT id,name,is_activated FROM member WHERE fgid = '$fgid'";
		$resultset = mysql_query($query);
		// Neu ton tai trong DB roi
		if($resultset != null && mysql_num_rows ($resultset) > 0){
			while($rows = mysql_fetch_array($resultset)){
				$_SESSION["user"] = $rows["id"];
				$_SESSION["is_activated"] = $rows["is_activated"];
				$_SESSION["name"] = $rows["name"];
			}
		}
		// Neu chua ton tai trong db
		if(mysql_num_rows ($resultset) <= 0){
			$q2 = "INSERT INTO `member`(`id`, `fgid`, `name`, `email`,`ngay_tham_gia`) ".
					 			"VALUES (NULL,'$fgid','$fbfullname','$email',CURDATE())";
			mysql_query($q2);
			if(isset($_SESSION["ref"])){
				$refID = $_SESSION["ref"];
				$query = "UPDATE member SET so_nguoi_gioi_thieu = so_nguoi_gioi_thieu + 1,so_luot_choi_ref_con_lai = so_luot_choi_ref_con_lai + 2 WHERE id = ".$refID;
				$query = "";
				unset($_SESSION["ref"]);
			}
			
			// Get back
			$query22 = "SELECT id,name,is_activated FROM member WHERE fgid = '$fgid'";
			$resultset22 = mysql_query($query);
			if($resultset22 != null && mysql_num_rows ($resultset22) > 0){
				while($rows22 = mysql_fetch_array($resultset22)){
					$_SESSION["user"] = $rows22["id"];
					$_SESSION["is_activated"] = $rows22["is_activated"];
					$_SESSION["name"] = $rows22["name"];
				}
			}
		}
	}
	/**
	 * Get luot choi con lai
	 */
	function getLuotChoiConLai(){
		$query = "SELECT so_luot_choi_con_lai, so_luot_choi_ref_con_lai FROM member WHERE id = ".$_SESSION["user"];
		//echo $query;
		$resultset = mysql_query($query);
		$ret = 0;
		if($resultset != null){
			while($rows = mysql_fetch_assoc($resultset)){
				$ret1 = intval($rows["so_luot_choi_con_lai"]);
				$ret2 = intval($rows["so_luot_choi_ref_con_lai"]);
				$ret = $ret1 + $ret2;
			}
		}
		return $ret;
	}
?>